const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

// 数据库操作模块
const dbOperations = {
  async connect() {
    try {
      await client.connect();
      console.log("Connected to MongoDB");
      return client.db("vegetable").collection("vegetable");
    } catch (error) {
      console.error("Error connecting to MongoDB", error);
      throw error;
    }
  },
  async insertDocument(collection, document) {
    try {
      const result = await collection.insertOne(document);
      console.log("Document inserted successfully:", result);
      return result;
    } catch (error) {
      console.error("Error inserting document", error);
      throw error;
    }
  },
  async findDocument(collection, query) {
    try {
      const document = await collection.findOne(query);
      console.log("Found document:", document);
      return document;
    } catch (error) {
      console.error("Error finding document", error);
      throw error;
    }
  },
  async updateDocument(collection, filter, update) {
    try {
      const result = await collection.updateOne(filter, update);
      console.log("Update result:", result);
      return result;
    } catch (error) {
      console.error("Error updating document", error);
      throw error;
    }
  },
  async deleteDocument(collection, query) {
    try {
      const result = await collection.deleteOne(query);
      console.log("Delete result:", result);
      return result;
    } catch (error) {
      console.error("Error deleting document", error);
      throw error;
    }
  },
};

module.exports = dbOperations;